package redis

import kotlinx.serialization.json.Json
import org.example.seri.Data
import org.example.seri.Dataj
import org.redisson.Redisson
import org.redisson.api.RScript
import org.redisson.api.RedissonClient
import org.redisson.config.Config

object RedissonProtobufExample {
    fun createClient(): RedissonClient {
        val config = Config()
        // 配置Redisson使用DB1数据库
        config.useSingleServer()
            .setConnectionMinimumIdleSize(1000)
            .setConnectionPoolSize(5000)
            .setAddress("redis://192.168.189.4:6379")
            .setDatabase(1).setPassword("123456")

//        config.setCodec(ProtobufCodec())
        return Redisson.create(config)
    }

    @JvmStatic
    fun main(args: Array<String>) {
        val client = createClient()
        println("开始测试...")
        try {
//            val bucket = client.getBucket<Data>("ddd1")
//            bucket.set(
//                Data(
//                    111, 222, 3333, "hello world 卡霍夫卡换卡的说法是？",
//                    listOf("qw", "ddd", "retert"), mapOf("qw" to "qw", "ddd" to "ddd", "retert" to "retert")
//                )
//            )
//            val data = bucket.get()
//            println(Json.encodeToString(data))

            val script = client.script
            val luaScript = """
                local uid = redis.call('GET', 'token:' .. ARGV[1])
                if not uid or uid == '' then return nil end
                return redis.call('GET', 'user:' .. uid)
            """.trimIndent()
            val scriptSha = script.scriptLoad(luaScript)

            val l = System.currentTimeMillis()
//            for (i in 1..200000) {
//                val result = script.eval<Dataj>(
//                    RScript.Mode.READ_WRITE,
//                    luaScript,
//                    RScript.ReturnType.VALUE,
//                    emptyList(),
//                    ""
//                )
////                println(result)
//            }
            val l1 = System.currentTimeMillis()
            for (i in 1..200000) {
                val result = script.evalSha<Dataj>(
                    RScript.Mode.READ_WRITE,
                    scriptSha,
                    RScript.ReturnType.VALUE,
                    emptyList(),
                    ""
                )
//                println(result)
            }
            val l2 = System.currentTimeMillis()

            println("lua time: ${l1 - l} ${l2 - l1}")
        } finally {
            client.shutdown()
        }
    }
}